package org.realogic.cfm.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class PropertiesLoader {
	
	
	private static Logger LOGGER = Logger.getLogger(PropertiesLoader.class);

	public static Properties load(File file) {
		if (file == null)
			throw new IllegalArgumentException("Parameter 'file' can't be null.");
		if ((!file.exists()) || (!file.isFile()))
			throw new IllegalArgumentException("Properties file not exists:" + file.getAbsolutePath());
		String fm = file.getName();
		Properties props = new Properties();
		if (fm.endsWith(".xml")) {
			try {
				SAXReader builder = new SAXReader();
				Document doc = builder.read(file);
				Element root = doc.getRootElement();
				@SuppressWarnings("unchecked")
				List<Element> childrenList = root.elements();
				for (Element child : childrenList) {
					parseElement(child, "", props);
				}
			} catch (Exception e) {
				LOGGER.error("Error parsing XML file:" + file.getAbsolutePath(), e);
			}
		} else if (fm.endsWith(".properties")) {
			InputStream is = null;
			try {
				is = new FileInputStream(file);
				props.load(is);
			} catch (Exception e) {
				LOGGER.error("Error loading properties file:" + file.getAbsolutePath(), e);
			} finally {
				try {
					if (is != null){
						is.close();
					}
				} catch (IOException localIOException2) {
					
				}
			}
		} else {
			throw new IllegalArgumentException("Unsupported properties file type:" + file.getAbsolutePath());
		}
		return props;
	}

	@SuppressWarnings("unchecked")
	private static void parseElement(Element ele, String fkey, Properties props) {
		String name = ele.getName();
		String text = ele.getText();
		String key = fkey;
		List<Element> childrenList = ele.elements();
		if (key.length() > 0)
			key = key + ".";
		key = key + name;

		if (((text != null) && (!"".equals(text.trim()))) || (childrenList.size() == 0)) {
			putProperty(key, text, props);
		}
		List<Attribute> attrList = ele.attributes();
		for (Attribute attr : attrList) {
			String attKey = key + "." + attr.getName();
			String attText = attr.getValue();
			putProperty(attKey, attText, props);
		}
		for (Element child : childrenList) {
			parseElement(child, key, props);
		}
	}

	private static void putProperty(String key, String text, Properties props) {
		if (props.containsKey(key)) {
			String tmp = props.getProperty(key);
			props.put(key, tmp + "|" + text);
		} else {
			props.put(key, text);
		}
	}
}